// src/containers/Login/index.jsx - 更新的登录组件
import { useState } from 'react'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { useAuth } from '../../contexts/AuthContext'
import './style.css'

const Login = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const { login } = useAuth()
  
  const [formData, setFormData] = useState({
    email: '',
    password: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  // 获取登录前的页面，如果没有则默认到首页
  const from = location.state?.from?.pathname || '/home'

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    })
    // 清除错误信息
    if (error) {
      setError('')
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!formData.email.trim()) {
      setError('请输入邮箱地址')
      return
    }
    
    if (!formData.password.trim()) {
      setError('请输入密码')
      return
    }
    
    setLoading(true)
    setError('')
    
    try {
      const result = await login(formData.email, formData.password)
      
      if (result.success) {
        // 登录成功，跳转到目标页面
        navigate(from, { replace: true })
      } else {
        setError(result.message || '登录失败')
      }
    } catch (err) {
      setError('登录过程中出现错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="auth-page">
      <div className="auth-container">
        <div className="auth-header">
          <h1>欢迎回来</h1>
          <p>登录您的智慧面试账户</p>
        </div>
        
        <form className="auth-form" onSubmit={handleSubmit}>
          {error && (
            <div className="error-alert">
              <span className="error-icon">⚠️</span>
              <span>{error}</span>
            </div>
          )}
          
          <div className="form-group">
            <label htmlFor="email">邮箱地址</label>
            <input
              type="email"
              id="email"
              name="email"
              value={formData.email}
              onChange={handleChange}
              placeholder="请输入您的邮箱"
              className={error && !formData.email ? 'error' : ''}
              required
            />
          </div>
          
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <div className="password-input">
              <input
                type={showPassword ? 'text' : 'password'}
                id="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                placeholder="请输入您的密码"
                className={error && !formData.password ? 'error' : ''}
                required
              />
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? '🙈' : '👁️'}
              </button>
            </div>
          </div>
          
          <div className="form-options">
            <label className="checkbox-label">
              <input type="checkbox" />
              <span>记住我</span>
            </label>
            <Link to="/forgot-password" className="forgot-link">
              忘记密码？
            </Link>
          </div>
          
          <button 
            type="submit" 
            className="auth-btn"
            disabled={loading}
          >
            {loading ? (
              <div className="button-loading">
                <div className="loading-spinner"></div>
                <span>登录中...</span>
              </div>
            ) : (
              '登录'
            )}
          </button>
        </form>
        
        <div className="demo-accounts">
          <h4>📝 测试账号</h4>
          <div className="demo-list">
            <div className="demo-account">
              <strong>邮箱：</strong>test@example.com<br />
              <strong>密码：</strong>12345678
            </div>
            <div className="demo-account">
              <strong>邮箱：</strong>admin@example.com<br />
              <strong>密码：</strong>admin123
            </div>
          </div>
        </div>
        
        <div className="auth-divider">
          <span>或</span>
        </div>
        
        <div className="social-login">
          <button 
            type="button" 
            className="social-btn google"
            onClick={() => setError('第三方登录功能开发中...')}
          >
            <span>🔍</span>
            使用 Google 登录
          </button>
          <button 
            type="button" 
            className="social-btn wechat"
            onClick={() => setError('第三方登录功能开发中...')}
          >
            <span>📱</span>
            使用微信登录
          </button>
        </div>
        
        <div className="auth-footer">
          <p>
            还没有账户？
            <Link to="/register" className="auth-link">
              立即注册
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}

export default Login